import base64

import requests
import os
from Crypto.Cipher import AES


def check_ruijie():  # 判断是否在校园网内
    eportal_url = "10.0.11.5"  # 学校认证网关ip
    res = os.system(f"ping {eportal_url} -n 1")
    if res == 0:
        return True
    else:
        return False


def check_connection():  # 能否连接互联网
    res = os.system(f"ping www.baidu.com -n 1")
    if res == 0:
        return True
    else:
        return False


def down_internet(userIndex):
    url = 'http://10.0.11.5/eportal/InterFace.do?method=logout'
    data = {
        "method": "logout",
        "userIndex": userIndex
    }
    resp = requests.post(url, data=data)
    resp.encoding = "utf-8"
    if resp.status_code == 200:
        print("下线成功！")
    else:
        print("下线失败，请再试一下！")


def AES_Encrypt(key, data):
    vi = '0102030405060708'
    pad = lambda s: s + (16 - len(s) % 16) * chr(16 - len(s) % 16)
    data = pad(data)
    # 字符串补位
    cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
    encryptedbytes = cipher.encrypt(data.encode('utf8'))
    # 加密后得到的是bytes类型的数据
    encodestrs = base64.b64encode(encryptedbytes)
    # 使用Base64进行编码,返回byte字符串
    enctext = encodestrs.decode('utf8')
    # 对byte字符串按utf-8进行解码
    return enctext


def AES_Decrypt(key, data):
    vi = '0102030405060708'
    data = data.encode('utf8')
    encodebytes = base64.decodebytes(data)
    # 将加密数据转换位bytes类型数据
    cipher = AES.new(key.encode('utf8'), AES.MODE_CBC, vi.encode('utf8'))
    text_decrypted = cipher.decrypt(encodebytes)
    unpad = lambda s: s[0:-s[-1]]
    text_decrypted = unpad(text_decrypted)
    # 去补位
    text_decrypted = text_decrypted.decode('utf8')
    return text_decrypted


def write(data):
    key = 'jl2DaD4nBf2fcRSf'  # 密钥
    enctext = AES_Encrypt(key, data)
    with open("pwd.txt", mode="w", encoding="utf-8") as f:
        f.write(enctext)


def read():
    key = 'jl2DaD4nBf2fcRSf'
    with open("pwd.txt", mode="r", encoding="utf-8") as f:
        enctext = f.read()
    text = AES_Decrypt(key, enctext)
    return text


def reconnect():
    router_ip = "192.168.1.1"
    # 构造登录 URL
    login_url = "http://192.168.1.1/cgi-bin/luci/"
    # 构造执行命令的 URL
    reconnect_url = "http://192.168.1.1/cgi-bin/luci/admin/network/iface_reconnect/wan1"

    session = requests.Session()
    # 登录 OpenWrt 路由器
    login_data = {
        'luci_username': "root",
        'luci_password': "password"
    }
    session.post(login_url, data=login_data)
    print(f"session_token:{session.cookies}")

    # 构造 POST 请求的表单数据，包括 CSRF Token
    sysauth = session.cookies["sysauth"]
    print(sysauth)
    command_data = {
        'token': sysauth,
        # 其他需要的表单字段
    }
    # 发送执行命令的 POST 请求
    resp2 = session.post(reconnect_url, data=command_data)
    if resp2.status_code == 200:
        print("重启接口成功！")
    else:
        print(f"接口重启失败{resp2.status_code}")


def test_connect(url):  # 测试指定网络连接状态
    # 校园网内才会自动跳转：http://10.0.11.5
    try:
        requests.get(url, timeout=5)
        return True
    except Exception as e:
        return False

if __name__ == '__main__':
    # 使用获取到的 CSRF Token 执行命令
    # reconnect()
    print(test_connect("http://10.0.11.5"))

